package com.kq.myofficialaccount.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.kq.myofficialaccount.exception.BusinessException;
import com.kq.myofficialaccount.model.entity.User;
import com.kq.myofficialaccount.service.UserService;
import com.kq.myofficialaccount.service.WxService;
import com.kq.myofficialaccount.utils.TokenUtil;
import com.kq.myofficialaccount.utils.WxUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WxServiceImpl implements WxService {
    @Resource
    UserService userService;

    @Resource
    RedisServiceImpl redisService;

    @Override
    public String WxLogin(String openId) throws JsonProcessingException {
        // 先去数据库中查询是否有 openId 如果有则表明已经注册
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mpOpenId", openId);
        User one = userService.getOne(queryWrapper);
        String token = TokenUtil.generateShortToken();
        String key = openId + "LoginToken";
        if (one == null) {
            // 用户还没有注册，调用注册方法
            Map<String, String> userBaseMes = WxUtil.getUserBaseMes(openId);
            if (userBaseMes.get("subscribe").equals("0")) {
                throw new BusinessException(400, "无法拉取用户信息");
            }
            User user = new User();
            // 保存用户的 unionId 和 openId
            user.setMpOpenId(openId);
            user.setUnionId(userBaseMes.get("unionid"));
            user.setUserName("微信用户_" + openId);
            //TODO:完成 accessKey 的获取
            boolean save = userService.save(user);
            if (!save) {
                throw new BusinessException(400, "系统内部错误");
            }
        }
        // 在 Redis 中存储密钥信息
        redisService.setExpireString(key, token, 120, TimeUnit.SECONDS);
        return token;
    }

}
